﻿using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.DB.ExtensibleStorage;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using MS.WindowsAPICodePack.Internal;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using ZhuXingFamilys.ExportExcel.entity;
using ZhuXingFamilys.ExportExcel.utils;
using ZhuXingFamilys.fimaly;
using ZhuXingFamilys.Help;
using ZhuXingFamilys.MainViewModel;
using ZhuXingFamilys.User;
using ZhuXingFamilys.utils;
using Binding = System.Windows.Data.Binding;
using Ceiling = Autodesk.Revit.DB.Ceiling;
using CellType = NPOI.SS.UserModel.CellType;
using ComboBox = System.Windows.Controls.ComboBox;
using Floor = Autodesk.Revit.DB.Floor;
using Point = System.Windows.Point;
using Visibility = System.Windows.Visibility;
using Microsoft.Win32;


namespace ZhuXingFamilys.ExportExcel
{
    /// <summary>
    /// ExportToExcel.xaml 的交互逻辑
    /// </summary>
    /// 
    public partial class ExportToExcel : Window, INotifyPropertyChanged
    {
        private static ExportToExcel staticInstance = null;

        // 当前Document原始数据
        private ObservableCollection<excelData> List = new ObservableCollection<excelData>();

        // Revit链接中的数据
        private ObservableCollection<excelData> ListFromLinks = new ObservableCollection<excelData>();

        // 专业树切换数据
        private ObservableCollection<excelData> excelListByCategory = new ObservableCollection<excelData>();

        // 条件过滤数据
        private ObservableCollection<excelData> filterAList = new ObservableCollection<excelData>();
        private ObservableCollection<excelData> filterBList = new ObservableCollection<excelData>();

        private ObservableCollection<excelData> filterCList = new ObservableCollection<excelData>();

        // 项目名称
        private string projectName = string.Empty;

        // 清单规则树
        private List<RulesNode> rulesNodeList = new List<RulesNode>();

        // 当前登录用户
        private readonly string userName = UserLoginCommand.UserName;

        // 排序视图
        private ICollectionView viewForSort = null;

        //ExternalCommandData commandData;
        private UIApplication uiApp;
        // 后台任务
        private BackgroundWorker backWork = new BackgroundWorker();

        // 保存数据外部事件
        private StoreElement storeElement;

        private ExternalEvent storeElementEvent;

        // 数据存储器名称
        private string dataStorageName = "ZhuXingFamilysDataStorage";

        // 数据存储key
        private string key = "ScheduleList";

        // 工程名称实体 用于保存GUID
        public SchemaName schemaName = null;

        // 扣减事件
        private LianJie lianjie;

        private ExternalEvent lianjieElementEvent;

        // 扣减完成是否刷新
        private bool isLianjieDone = false;

        // 子窗口
        private SelectSchema selectSchema;

        // 子窗口的位置Left
        private double _leftSubWnd = 0;

        public double LeftSubWnd
        {
            get { return _leftSubWnd; }
            set
            {
                if (_leftSubWnd != value)
                {
                    _leftSubWnd = value;
                    OnPropertyChanged("LeftSubWnd");
                }
            }
        }

        // 子窗口的位置Top
        private double _topSubWnd = 0;

        public double TopSubWnd
        {
            get { return _topSubWnd; }
            set
            {
                if (_topSubWnd != value)
                {
                    _topSubWnd = value;
                    OnPropertyChanged("TopSubWnd");
                }
            }
        }

        // 子窗口的高度
        private double _heightSubWnd = 0;

        public double HeightSubWnd
        {
            get { return _heightSubWnd; }
            set
            {
                if (_heightSubWnd != value)
                {
                    _heightSubWnd = value;
                    OnPropertyChanged("HeightSubWnd");
                }
            }
        }

        // 已保存的明细表
        IList<SchemaName> savedSchemaNameList;

        public ExportToExcel(UIApplication UIApp)
        {
            this.uiApp = UIApp;
            //ui库使用
            ColorZoneAssist.SetMode(new GroupBox(), ColorZoneMode.Light);
            Hue hue = new Hue("name", System.Windows.Media.Color.FromArgb(1, 2, 3, 4),
                System.Windows.Media.Color.FromArgb(1, 5, 6, 7));

            InitializeComponent();
            storeElement = new StoreElement();
            storeElementEvent = ExternalEvent.Create(storeElement);

            lianjie = new LianJie();
            lianjieElementEvent = ExternalEvent.Create(lianjie);

            // 窗口尺寸发生变化
            this.SizeChanged += new SizeChangedEventHandler(ExportToExcel_Resize);
            // 窗口位置发生变化
            CompositionTarget.Rendering += new EventHandler(WindowPositionChange);
        }

        // 窗口尺寸发生变化事件
        private void ExportToExcel_Resize(object sender, SizeChangedEventArgs e)
        {
            if (this.WindowState == WindowState.Maximized)
            {
                double StackPanelWidth = 260;
                double x1 = SystemParameters.PrimaryScreenWidth; //得到屏幕整体宽度
                double y1 = SystemParameters.PrimaryScreenHeight; //得到屏幕整体高度
                // excel表格列尺寸根据窗口尺寸变化
                ListView1.Width = x1 - StackPanelWidth;
                ExcelId.Width = (x1 - StackPanelWidth) * 0.08;
                ExcelCode.Width = (x1 - StackPanelWidth) * 0.20;
                ExcelName.Width = (x1 - StackPanelWidth) * 0.20;
                ExcelFeatures.Width = (x1 - StackPanelWidth) * 0.2;
                ExcelNum.Width = (x1 - StackPanelWidth) * 0.10;
                ExcelQuantitiesname.Width = (x1 - StackPanelWidth) * 0.1;
                ExcelCompany.Width = (x1 - StackPanelWidth) * 0.1;
                // 表格高度
                ListView1.Height = y1 - 230;
                // 子窗口高度
                HeightSubWnd = this.Height;
                // 选项高度
                categoryTreeView.Height = y1 - 260;
            }
            else
            {
                // 表格宽度
                double StackPanelWidth = 275;
                ListView1.Width = this.Width - StackPanelWidth;
                ExcelId.Width = (this.Width - StackPanelWidth) * 0.08;
                ExcelCode.Width = (this.Width - StackPanelWidth) * 0.20;
                ExcelName.Width = (this.Width - StackPanelWidth) * 0.20;
                ExcelFeatures.Width = (this.Width - StackPanelWidth) * 0.2;
                ExcelNum.Width = (this.Width - StackPanelWidth) * 0.10;
                ExcelQuantitiesname.Width = (this.Width - StackPanelWidth) * 0.1;
                ExcelCompany.Width = (this.Width - StackPanelWidth) * 0.1;
                // 表格高度
                ListView1.Height = this.Height - 200;
                // 子窗口高度
                HeightSubWnd = this.Height;
                // 选项高度
                categoryTreeView.Height = this.Height - 230;
            }
        }

        // 窗口位置发生变化
        private void WindowPositionChange(object sender, EventArgs e)
        {
            if (this.IsLoaded && this.IsActive)
            {
                Point temPoint = this.PointToScreen(new Point(0, 0));
                //selectSchema.Owner = this;
                LeftSubWnd = temPoint.X + this.Width - 22;
                TopSubWnd = temPoint.Y - 31;
            }
        }

        // 窗口加载完成后
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // 设置多线程任务
            backWork.WorkerReportsProgress = true;
            backWork.WorkerSupportsCancellation = false;
            backWork.ProgressChanged += BackWork_ProgressChanged;
            backWork.DoWork += backWork_DoWork;
            backWork.RunWorkerCompleted += backWork_RunWorkerCompleted;

            //ElementCategoryFilter filter2 = new ElementCategoryFilter(BuiltInCategory.INVALID);
            //Document doc = commandData.Application.ActiveUIDocument.Document;
            //FilteredElementCollector collector = new FilteredElementCollector(doc);
            //List<Element> listElement = collector.WherePasses(filter2).WhereElementIsNotElementType().ToList();
            if (this.rulesNodeList != null)
            {
                rulesNodeList.Clear();
            }

            // 加载过滤器和排序字典
            A1.ItemsSource = B1.ItemsSource = C1.ItemsSource = OrderA1.ItemsSource =
                OrderB1.ItemsSource = OrderC1.ItemsSource = selectDateDictionary.DateType();
            A2.ItemsSource = B2.ItemsSource = C2.ItemsSource = selectDateDictionary.OperationType();
            OrderA2.ItemsSource = OrderB2.ItemsSource = OrderC2.ItemsSource = selectDateDictionary.OrderType();

            // 初始化空专业树
            categoryTreeView.ItemsSource = CategoryTree.getCategoryTree(null);

            excelDataInitialization();
        }

        // 一键算量按钮点击事件
        private void loadExcelButton_Click(object sender, RoutedEventArgs e)
        {
            excelDataInitialization();
        }

        // 窗口关闭事件
        private void WindowOnClosed(object sender, System.EventArgs e)
        {
            staticInstance = null;
        }
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (backWork.IsBusy)
            {
                e.Cancel = true;
                MessageBox.Show("请等待计算完成...", "提示");
            }
        }
        // 获取实例
        public static ExportToExcel GetInstance(UIApplication uiApp)
        {
            if (staticInstance == null)
            {
                staticInstance = new ExportToExcel(uiApp);
            }

            return staticInstance;
        }

        // 获取实例
        public static ExportToExcel GetInstance()
        {
            return staticInstance;
        }

        // 刷新按钮点击事件
        private void LoadData_Click(object sender, RoutedEventArgs e)
        {
            ListView1.Visibility = System.Windows.Visibility.Collapsed;
            this.excelDataInitialization();
        }

        // 表格上移
        private void up_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (ListView1.SelectedItem != null)
            {
                excelData selData = ListView1.SelectedItem as excelData;
                List<excelData> el = this.ListView1.Items.Cast<object>().Select(x => x as excelData).ToList();
                int index = el.IndexOf(selData);
                if (index == 0)
                    return;
                el.RemoveAt(index);
                index = index - 1;
                el.Insert(index, selData);
                ListView1.ItemsSource = el;
            }
            else
            {
                MessageBox.Show("请先选中需要调整的行", "提示");
            }
        }

        // 表格下移
        private void down_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (ListView1.SelectedItem != null)
            {
                excelData selData = ListView1.SelectedItem as excelData;
                List<excelData> el = this.ListView1.Items.Cast<object>().Select(x => x as excelData).ToList();
                int index = el.IndexOf(selData);
                if (index == ListView1.Items.Count - 1)
                    return;
                el.RemoveAt(index);
                index = index + 1;
                el.Insert(index, selData);
                ListView1.ItemsSource = el;
            }
            else
            {
                MessageBox.Show("请先选中需要调整的行", "提示");
            }
        }

        // 双击定位族
        private void ListView1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                DataGrid datagrid = sender as DataGrid;
                System.Windows.Point aP = e.GetPosition(datagrid);
                IInputElement obj = datagrid.InputHitTest(aP);
                DependencyObject target = obj as DependencyObject;
                while (target != null)
                {
                    if (target is DataGridRow)
                    {
                        UIDocument uiDoc = uiApp.ActiveUIDocument;

                        excelData excelInDataGrid = datagrid.CurrentItem as excelData;
                        string familyNumber = excelInDataGrid.FamilyNumber;
                        string name = excelInDataGrid.Name;

                        var selection = uiDoc.Selection.GetElementIds();
                        if (selection.Count != 0)
                        {
                            selection.Clear();
                        }

                        foreach (excelData e1 in excelListByCategory)
                        {
                            if (e1.FamilyNumber.Equals(familyNumber) && e1.Name.Equals(name))
                            {
                                string[] elementIds = e1.elementId.Split(',');
                                foreach (string elementId in elementIds)
                                {
                                    selection.Add(new ElementId(int.Parse(elementId)));
                                }
                                //MessageBox.Show(e1.elementId);
                            }
                        }


                        uiDoc.Selection.SetElementIds(selection);

                        try
                        {
                            //聚焦元素
                            uiApp.ActiveUIDocument.ShowElements(selection);
                            uiApp.ActiveUIDocument.RefreshActiveView();
                            //最小化窗口
                            this.WindowState = WindowState.Minimized;
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("双击定位暂不支持以“Revit链接”方式展示的模型，请单独打开操作", "提示");
                        }

                        break;
                    }

                    target = VisualTreeHelper.GetParent(target);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("双击定位不支持外部导入数据", "提示");
            }
        }

        // 工程量名称切换
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cb = (sender as System.Windows.Controls.ComboBox);
            excelData excel = cb.DataContext as excelData;
            string selected = cb.SelectedValue.ToString();
            // 如果是导入的外部数据
            if (excel.Num != 0 && excel.Area == 0 && excel.Length == 0 && excel.Volume == 0 && excel.NumCount == 0)
            {
                // 切换单位数据不发生变化
            }
            // 如果是生成或者加载的数据
            else
            {
                if (selected.Equals("数量"))
                {
                    excel.Num = excel.NumCount;
                    excel.Quantitiesname = "数量";
                }

                if (selected.Equals("体积"))
                {
                    excel.Num = excel.Volume;
                    excel.Quantitiesname = "体积";
                }

                if (selected.Equals("面积"))
                {
                    excel.Num = excel.Area;
                    excel.Quantitiesname = "面积";
                }

                if (selected.Equals("长度"))
                {
                    excel.Num = excel.Length;
                    excel.Quantitiesname = "长度";
                }
            }
        }

        // 是否包含链接中的图元	
        ObservableCollection<excelData> l1 = new ObservableCollection<excelData>();

        ObservableCollection<excelData> l2 = new ObservableCollection<excelData>();

        // 包含连接中的图元
        private void Links_Checked(object sender, RoutedEventArgs e)
        {
            // 合并excelDataList
            if (ListFromLinks != null && ListFromLinks.Count != 0)
            {
                if (List != null && List.Count != 0)
                {
                    l1 = List.Copy();
                }

                l2 = ListFromLinks.Copy();
                //将链接数据与主数据合并
                l1.AddRange(l2);
                // 生成专业树
                categoryTreeView.ItemsSource = CategoryTree.getCategoryTree(l1);
                // 生成数据
                excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(l1);
                excelListByCategory = categoryTree.getAll();
                ListView1.ItemsSource = excelListByCategory;
            }
            else
            {
                MessageBox.Show("未找到有效Revit链接，请检查", "提示");
                Links.IsChecked = false;
            }
        }

        // 不包含连接中的图元
        private void Links_Unchecked(object sender, RoutedEventArgs e)
        {
            // 生成专业树
            categoryTreeView.ItemsSource = CategoryTree.getCategoryTree(List);
            // 生成数据
            excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(List);
            excelListByCategory = categoryTree.getAll();
            ListView1.ItemsSource = excelListByCategory;
        }

        // 打开选择明细表窗口
        private void loadExcelWindow(object sender, MouseButtonEventArgs e)
        {
            loadExcelWindows();
        }

        // 打开明细表窗口逻辑
        public void loadExcelWindows()
        {
            if (selectSchema != null)
            {
                selectSchema.Close();
                selectSchema = null;
            }
            else
            {
                Document doc = uiApp.ActiveUIDocument.Document;
                // 获取已保存的清单表名称列表
                savedSchemaNameList = StoreElementReadInfo.GetSchemaList(doc, dataStorageName);

                selectSchema = new SelectSchema(uiApp, savedSchemaNameList);

                // 绑定与父窗口位置关系
                // 绑定位置左
                Binding temBindg = new Binding();
                temBindg.Source = this;
                temBindg.Mode = BindingMode.TwoWay;
                temBindg.Path = new PropertyPath("LeftSubWnd");
                selectSchema.SetBinding(Window.LeftProperty, temBindg);
                selectSchema.Owner = this;
                // 绑定位置上
                Binding temBindg2 = new Binding();
                temBindg2.Source = this;
                temBindg2.Mode = BindingMode.TwoWay;
                temBindg2.Path = new PropertyPath("TopSubWnd");
                selectSchema.SetBinding(Window.TopProperty, temBindg2);

                // 绑定窗口高度
                Binding temBindg3 = new Binding();
                temBindg3.Source = this;
                temBindg3.Mode = BindingMode.TwoWay;
                temBindg3.Path = new PropertyPath("HeightSubWnd");
                selectSchema.SetBinding(Window.HeightProperty, temBindg3);

                selectSchema.WindowStartupLocation = WindowStartupLocation.Manual;
                selectSchema.Show();
                selectSchema.Activate();

                string path = @"./icon/返回.png";
                this.loadWindowButton.Source = new BitmapImage(new Uri(path, UriKind.Relative));
                this.loadWindowButton.ToolTip = "返回";
            }
        }

        // 选择清单列表窗口关闭事件
        public void SelectSchema_Closed()
        {
            selectSchema = null;
            string path = @"./icon/右箭头.png";
            this.loadWindowButton.Source = new BitmapImage(new Uri(path, UriKind.Relative));
            this.loadWindowButton.ToolTip = "加载";
        }

        // 加载用户选择的明细表
        public void loadExcel(SchemaName sn)
        {
            if (sn != null)
            {
                this.schemaName = sn;
                //MessageBox.Show("选择的是：" + guid);
                UIDocument uidoc = uiApp.ActiveUIDocument;
                Document doc = uidoc.Document;
                IList<string> excelDataListStr = StoreElementReadInfo.GetEntity(doc, dataStorageName, sn.Guid, key);
                if (excelDataListStr != null && excelDataListStr.Count != 0)
                {
                    ObservableCollection<excelData> excelDatas = new ObservableCollection<excelData>();
                    foreach (string excelStr in excelDataListStr)
                    {
                        excelData excel = JsonConvert.JsonToObject<excelData>(excelStr);
                        excelDatas.Add(excel);
                    }

                    //初始化数据
                    List = excelDatas;
                    categoryTreeView.ItemsSource = CategoryTree.getCategoryTree(List);
                    excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(List);
                    excelListByCategory = categoryTree.getAll();
                    ListView1.ItemsSource = excelListByCategory;
                    this.ProjectName.Text = sn.Name;
                    ListView1.Visibility = System.Windows.Visibility.Visible;
                    loadExcelButton.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

        // 导入excel
        private void inport(object sender, MouseButtonEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();

            // 过滤文件扩展名，设置接受的扩展名
            openFileDlg.DefaultExt = ".xls|.xlsx";
            openFileDlg.Filter = "Excel|*.xls;*.xlsx";
            openFileDlg.Title = "导入清单表";
            // 设置初始目录
            // openFileDlg.InitialDirectory = this._path;

            // 调用ShowDialog方法显示对话框
            Nullable<bool> result = openFileDlg.ShowDialog();
            // 显示名称
            if (result == true)
            {
                try
                {
                    string path = openFileDlg.FileName;
                    string fileName = openFileDlg.SafeFileName;

                    using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        byte[] bytes = new byte[fileStream.Length];
                        fileStream.Read(bytes, 0, bytes.Length);
                        fileStream.Close();
                        // 把 byte[] 转换成 Stream
                        Stream stream = new MemoryStream(bytes);
                        // 根据实体类转换
                        ObservableCollection<excelData> uploadExcelData =
                            ExcelConvert.ToEntityStreamListForExcelData<excelData>(stream, fileName, true);
                        // 获取工程名称
                        schemaName = new SchemaName();
                        schemaName.Name = ExcelConvert.GetEntityName();
                        this.ProjectName.Text = schemaName.Name;
                        //初始化数据
                        List = uploadExcelData;
                        // 初始化不含Revit链接的专业树
                        categoryTreeView.ItemsSource = CategoryTree.getCategoryTree(List);
                        // 初始化包不含Revit链接的数据
                        excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(List);
                        excelListByCategory = categoryTree.getAll();
                        ListView1.ItemsSource = excelListByCategory;
                        ListView1.Visibility = System.Windows.Visibility.Visible;
                        loadExcelButton.Visibility = System.Windows.Visibility.Collapsed;
                        //System.Windows.Forms.MessageBox.Show("导入成功");
                    }
                }
                catch (Exception e3)
                {
                    if (e3.Message.Contains("另一进程使用"))
                    {
                        MessageBox.Show(e3.Message, "提示");
                    }
                    else if (e3.Message.Contains("未将对象引用设置到对象的实例"))
                    {
                        MessageBox.Show("excel格式错误，请重新导出模板，不要更改模板格式。", "提示");
                    }
                    else
                    {
                        MessageBox.Show("导入失败，原因：" + e3.Message, "提示");
                    }
                }
            }
        }

        // 导出到excel
        private void export(object sender, MouseButtonEventArgs e)
        {
            // 需要保存的数据
            List<excelData> exportList = this.ListView1.Items.Cast<object>().Select(x => x as excelData).ToList();
            if (exportList != null && exportList.Count != 0)
            {
                System.Windows.Forms.SaveFileDialog s = new System.Windows.Forms.SaveFileDialog();
                s.Filter = "Excel|*.xls|Excel|*.xlsx";
                s.Title = "导出清单表";
                s.DefaultExt = "Excel|*.xls";
                //获取文默认件扩展名
                // string str = s.DefaultExt;
                //用户点击"保存"后执行的逻辑
                if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    // 保存的目录
                    string fileName = s.FileName;

                    /// 导出逻辑
                    IWorkbook workbook = new HSSFWorkbook();
                    ISheet sheet = workbook.CreateSheet("Sheet1");
                    // 导出的字段
                    List<ComboBoxPairs> dateType = selectDateDictionary.DateType1();
                    //PropertyInfo[] pross = new excelData().GetType().GetProperties();

                    // 处理标题 第一行
                    ICellStyle style = workbook.CreateCellStyle();
                    style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                    style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                    IFont font = workbook.CreateFont();
                    font.IsBold = true;
                    font.FontHeightInPoints = 14;
                    style.SetFont(font);
                    //style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Double;
                    //style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Double;
                    //style.BorderRight = NPOI.SS.UserModel.BorderStyle.Double;
                    //style.BorderTop = NPOI.SS.UserModel.BorderStyle.Double;
                    IRow row0 = sheet.CreateRow(0);
                    ICell row0Cell = row0.CreateCell(0, CellType.String);
                    row0Cell.SetCellValue("分部分项工程量清单");
                    row0Cell.CellStyle = style;
                    // 合并单元格
                    sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dateType.Count));

                    // 处理项目名称 第二行
                    IRow row1 = sheet.CreateRow(1);
                    ICell row1Cell = row1.CreateCell(0, CellType.String);
                    row1Cell.SetCellValue("工程名称：" + ProjectName.Text);


                    // 处理表头 第三行
                    IRow row2 = sheet.CreateRow(2);
                    ICell row2Cell = null;
                    row2Cell = row2.CreateCell(0, CellType.String);
                    row2Cell.SetCellValue("序号");

                    for (int i = 0; i < dateType.Count; i++)
                    {
                        row2Cell = row2.CreateCell(i + 1, CellType.String);
                        row2Cell.SetCellValue(dateType[i]._Value);
                    }

                    // 处理内容 第四行开始
                    ICell cellContent = null;
                    for (int i = 0; i < exportList.Count; i++)
                    {
                        IRow row3 = sheet.CreateRow(i + 3);
                        // 处理序号
                        cellContent = row3.CreateCell(0, CellType.String);
                        cellContent.SetCellValue((i + 1).ToString());
                        // 处理其他字段
                        for (int j = 0; j < dateType.Count; j++)
                        {
                            string excelValue = string.Empty;
                            string title = dateType[j]._Value;
                            //if (title.Equals("序号"))
                            //{
                            //    excelValue = list[i].Id.ToString();
                            //}
                            if (title.Equals("项目编号"))
                            {
                                excelValue = exportList[i].Code.ToString();
                            }
                            else if (title.Equals("项目名称"))
                            {
                                excelValue = exportList[i].Name.ToString();
                            }
                            else if (title.Equals("项目特征"))
                            {
                                excelValue = exportList[i].Features.ToString();
                            }
                            else if (title.Equals("工程量名称"))
                            {
                                excelValue = exportList[i].Quantitiesname.ToString();
                            }
                            else if (title.Equals("工程数量"))
                            {
                                excelValue = exportList[i].Num.ToString();
                            }
                            else if (title.Equals("计量数量"))
                            {
                                excelValue = exportList[i].NumCount.ToString();
                            }
                            else if (title.Equals("计量单位"))
                            {
                                excelValue = exportList[i].Company.ToString();
                            }
                            else
                            {
                                excelValue = string.Empty;
                            }

                            cellContent = row3.CreateCell(j + 1, CellType.String);
                            cellContent.SetCellValue(excelValue);
                        }
                    }

                    // 创建文件
                    try
                    {
                        FileStream file = new FileStream(fileName, FileMode.Create);
                        workbook.Write(file);
                        file.Close();
                        workbook.Close();
                        MessageBox.Show("导出完成", "提示");
                    }
                    catch (Exception e2)
                    {
                        MessageBox.Show(e2.Message, "提示");
                    }
                }
            }
            else
            {
                MessageBox.Show("当前表格中没有数据", "提示");
            }
        }

        // 删除
        private void Button_Click_Delete(object sender, MouseButtonEventArgs e)
        {
            MessageBoxResult re = MessageBox.Show("此操作将删除已保存的明细表数据，确定吗？", "提示", MessageBoxButton.OKCancel);
            if (re == MessageBoxResult.OK)
            {
                // 删除存储
                deleteExcel(schemaName);

                // 刷新子窗口中数据
                if (selectSchema != null && schemaName != null)
                {
                    var item = savedSchemaNameList.Where(r => r.Name.Equals(schemaName.Name)).FirstOrDefault();
                    savedSchemaNameList.Remove(item);
                    selectSchema.reloadList(savedSchemaNameList);
                }

                // 处理视图
                schemaName = null;
                this.ProjectName.Text = "";
                this.ListView1.ItemsSource = null;
                this.ListView1.Visibility = System.Windows.Visibility.Hidden;
                orderButton.Visibility = System.Windows.Visibility.Collapsed;
                this.loadExcelButton.Visibility = System.Windows.Visibility.Visible;
            }
        }

        // 删除存储逻辑
        public void deleteExcel(SchemaName _schemaName)
        {
            if (_schemaName != null)
            {
                storeElement.type = 1;
                storeElement.dataStorageName = dataStorageName;
                storeElement.key = key;
                storeElement.scheduleName = _schemaName.Name;
                storeElementEvent.Raise();
            }
        }

        // 保存
        private void Button_Click_Save(object sender, MouseButtonEventArgs e)
        {
            UIDocument uidoc = uiApp.ActiveUIDocument;
            Document doc = uidoc.Document;
            // 保存的工程量清单名称
            string scheduleName = this.ProjectName.Text;
            if (scheduleName == "" || scheduleName == null)
            {
                MessageBox.Show("请填写工程名称", "提示");
            }
            else
            {
                // 关闭子窗口
                if (selectSchema != null)
                {
                    selectSchema.Close();
                }

                // 转换需要保存的数据 这里必须转换成string 否则revit不能识别
                List<excelData> viewList;
                List<string> saveList;

                viewList = this.ListView1.Items.Cast<object>().Select(x => x as excelData).ToList();
                if (viewList != null && viewList.Count != 0)
                {
                    saveList = new List<string>();
                    foreach (excelData excel in viewList)
                    {
                        string jsonstr = JsonConvert.ObjectToJSON<excelData>(excel);
                        saveList.Add(jsonstr);
                    }

                    storeElement.type = 0;
                    storeElement.dataStorageName = dataStorageName;
                    storeElement.key = key;
                    storeElement.scheduleName = scheduleName;
                    storeElement.saveList = saveList;
                    storeElementEvent.Raise();

                    schemaName = new SchemaName();
                    schemaName.Name = scheduleName;

                    // MessageBox.Show("保存成功", "提示");
                }
                else
                {
                    MessageBox.Show("当前表格数据为空", "提示");
                }
            }
        }

        // 项目名称信息
        private string GetProjectName()
        {
            UIDocument uidoc = uiApp.ActiveUIDocument;
            Document doc = uiApp.ActiveUIDocument.Document;

            ProjectInfo proj = doc.ProjectInformation;
            string param = proj.get_Parameter(BuiltInParameter.PROJECT_NAME).AsValueString(); //获取项目名称
            if (param != null && param != "")
            {
                return param;
            }

            string name = doc.PathName;
            name = name.Substring(name.LastIndexOf("\\") + 1);
            name = name.Replace(name.Substring(name.LastIndexOf(".")), "");
            if (name.Length > 9)
            {
                // 截取前8位
                name = name.Substring(0, 8);
            }

            return name;
        }

        // 过滤器确定&取消事件
        private void Filter_Button_Click(object sender, RoutedEventArgs e)
        {
            Button b = e.Source as Button;
            // 过滤器点击确定
            if ("确定".Equals(b.Content))
            {
                this.Filter_OK();
            }

            // 点击取消重置过滤器条件
            if ("取消".Equals(b.Content))
            {
                this.A1.SelectedValue = null;
                this.A2.SelectedValue = null;
                this.A3.Text = null;
                this.B1.SelectedValue = null;
                this.B2.SelectedValue = null;
                this.B3.Text = null;
                this.C1.SelectedValue = null;
                this.C2.SelectedValue = null;
                this.C3.Text = null;
                ListView1.ItemsSource = excelListByCategory;
            }
        }

        // 排序功能
        private void Order_Button_Click(object sender, RoutedEventArgs e)
        {
            Button b = e.Source as Button;
            string A1 = OrderA1.SelectedValue as string;
            string A2 = OrderA2.SelectedValue as string;
            string B1 = OrderB1.SelectedValue as string;
            string B2 = OrderB2.SelectedValue as string;
            string C1 = OrderC1.SelectedValue as string;
            string C2 = OrderC2.SelectedValue as string;

            if ("确定".Equals(b.Content))
            {
                if (viewForSort != null && viewForSort.SortDescriptions != null)
                {
                    viewForSort.SortDescriptions.Clear();
                }

                viewSort(A1, A2);
                viewSort(B1, B2);
                viewSort(C1, C2);
            }

            if ("取消".Equals(b.Content))
            {
                this.OrderA1.SelectedValue = null;
                this.OrderA2.SelectedValue = null;
                this.OrderB1.SelectedValue = null;
                this.OrderB2.SelectedValue = null;
                this.OrderC1.SelectedValue = null;
                this.OrderC2.SelectedValue = null;
                if (viewForSort != null && viewForSort.SortDescriptions != null)
                {
                    viewForSort.SortDescriptions.Clear();
                    viewForSort.Refresh();
                }
            }
        }

        private void Filter_OK()
        {
            string ConditionA1 = this.A1.SelectedValue as string;
            string ConditionA2 = this.A2.SelectedValue as string;
            string ConditionA3 = this.A3.Text;

            string ConditionB1 = this.B1.SelectedValue as string;
            string ConditionB2 = this.B2.SelectedValue as string;
            string ConditionB3 = this.B3.Text;

            string ConditionC1 = this.C1.SelectedValue as string;
            string ConditionC2 = this.C2.SelectedValue as string;
            string ConditionC3 = this.C3.Text;
            //过滤条件A
            if (ConditionA1 != null && ConditionA2 != null && ConditionA3 != "" && ConditionB3 == "" &&
                ConditionC3 == "")
            {
                // 根据条件过滤
                filterAList = FilterForQuantities.filter(ConditionA1, ConditionA2, ConditionA3, excelListByCategory);
                // 重新生成列表
                ListView1.ItemsSource = filterAList;
                // 根据id字段升序排列
            }

            //过滤条件A+B
            if (ConditionA1 != null && ConditionA2 != null && ConditionA3 != "" && ConditionB1 != null &&
                ConditionB2 != null && ConditionB3 != "" && ConditionC3 == "")
            {
                // 根据条件过滤
                filterBList = FilterForQuantities.filter(ConditionB1, ConditionB2, ConditionB3, filterAList);
                // 重新生成列表
                ListView1.ItemsSource = filterBList;
                // 根据id字段升序排列
            }

            //过滤条件A+B+C
            if (ConditionA1 != null && ConditionA2 != null && ConditionA3 != "" && ConditionB1 != null &&
                ConditionB2 != null && ConditionB3 != "" && ConditionC1 != null && ConditionC2 != null &&
                ConditionC3 != "")
            {
                // 根据条件过滤
                filterCList = FilterForQuantities.filter(ConditionC1, ConditionC2, ConditionC3, filterBList);
                // 重新生成列表
                ListView1.ItemsSource = filterCList;
                // 根据id字段升序排列
            }
        }

        // 过滤器输入框检测空内容
        private void Filter_TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            System.Windows.Controls.TextBox tb = e.Source as System.Windows.Controls.TextBox;
            // 检测过滤条件A
            if ("A3".Equals(tb.Name))
            {
                if ("".Equals(tb.Text))
                {
                    ListView1.ItemsSource = excelListByCategory;
                }
            }
            else if ("B3".Equals(tb.Name))
            {
                if ("".Equals(tb.Text))
                {
                    //currentFilter = 1;
                    ListView1.ItemsSource = filterAList;
                }
            }
            else if ("C3".Equals(tb.Name))
            {
                if ("".Equals(tb.Text))
                {
                    ListView1.ItemsSource = filterBList;
                }
            }
        }

        // 选项&设置切换
        private void option_Click(object sender, RoutedEventArgs e)
        {
            if (e.Source is Button)
            {
                Button b = e.Source as Button;

                if (b.Content.Equals("选项"))
                {
                    this.optionButton.IsEnabled = false;
                    this.setupButton.IsEnabled = true;
                    this.setupSideBar.Visibility = System.Windows.Visibility.Collapsed;
                    this.optionSideBar.Visibility = System.Windows.Visibility.Visible;
                }
                else if (b.Content.Equals("设置"))
                {
                    this.optionButton.IsEnabled = true;
                    this.setupButton.IsEnabled = false;
                    this.setupSideBar.Visibility = System.Windows.Visibility.Visible;
                    this.optionSideBar.Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

        // 设置中的选项卡切换事件
        private void filterTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int lastIndex = 0;
            if (e.RemovedItems != null && e.RemovedItems.Count != 0 && e.RemovedItems[0] is TabItem)
            {
                TabItem last = e.RemovedItems[0] as TabItem;
                if (last != null && last.Header.ToString() == "排序")
                {
                    lastIndex = 1;
                }
            }

            // 加载清单规则
            //if (this.filterTabControl.SelectedIndex == 2)
            if (this.filterTabControl.SelectedIndex == 2)
            {
                RulesWindow rw = new RulesWindow(userName);
                rw.RulesChangeEvent += new RulesChangeHandler(deduction);
                rw.Show();
                rw.Activate();
                this.filterTabControl.SelectedIndex = lastIndex;
            }
        }

        // 扣减实现
        private void deduction()
        {
            RulesTree rt = new RulesTree(userName);
            List<RulesNode> rulesList = rt.getRulesList();
            lianjie.rulesNodeList = rulesList;
            lianjieElementEvent.Raise();
            WindowState = WindowState.Minimized;
            isLianjieDone = true;
        }

        // 专业切换事件
        private void categoryTreeView_SelectedItemChanged(object sender, RoutedEventArgs e)
        {
            DefinitionNode dfi = categoryTreeView.SelectedItem as DefinitionNode;
            ObservableCollection<excelData> categorySelectedItemChanged = new ObservableCollection<excelData>();
            if (Links.IsChecked == false)
            {
                categorySelectedItemChanged = List.Copy();
            }
            else
            {
                categorySelectedItemChanged = l1.Copy();
            }

            excelListByCategory.Clear();
            // 项目名称
            StringBuilder proName = new StringBuilder();
            // 点击专业
            if (dfi.Parent == null && !dfi.SpecialitieId.Equals("0"))
            {
                proName.Clear();
                proName.Append(projectName).Append("_").Append(dfi.Name);
                excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(categorySelectedItemChanged, dfi);
                excelListByCategory = categoryTree.getForSpecialty();
            }

            // 点击全部
            else if (dfi.Parent == null && dfi.SpecialitieId.Equals("0"))
            {
                proName.Clear();
                proName.Append(projectName).Append("_").Append(dfi.Name);
                excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(categorySelectedItemChanged);
                excelListByCategory = categoryTree.getAll();
            }
            // 点击详细类型
            else if (dfi.Parent.Equals("类型"))
            {
                proName.Clear();
                proName.Append(projectName).Append("_").Append(dfi.SpecialitieId).Append("_").Append(dfi.Parent)
                    .Append("_").Append(dfi.Name);
                excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(categorySelectedItemChanged, dfi);
                excelListByCategory = categoryTree.getForDetailType();
            }
            // 点击详细楼层
            else if (dfi.Parent.Equals("楼层"))
            {
                proName.Clear();
                proName.Append(projectName).Append("_").Append(dfi.Name);
                excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(categorySelectedItemChanged, dfi);
                excelListByCategory = categoryTree.getForDetailedElevation();
            }
            // 点击“类型、楼层”
            else
            {
                excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(categorySelectedItemChanged, dfi);
                excelListByCategory = categoryTree.getOther();
            }

            ListView1.ItemsSource = excelListByCategory;
            // 根据id字段升序排列

            this.ProjectName.Text = proName.ToString();
        }

        //RulesWindow rw = null;
        // 规则清单树点击事件
        private void RulesNodeTreeView_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            //if (RulesNodeTreeView.SelectedItem is RulesNode)
            //{
            //    RulesNode rulesNode = RulesNodeTreeView.SelectedItem as RulesNode;
            //    if (rulesNode != null && rulesNode.Level == 2)
            //    {
            //        rw = new RulesWindow(rulesNode, userName);
            //        rw.ShowDialog();
            //    }
            //}
        }

        // 清单规则导入导出
        private void Rules_Import_Export(object sender, RoutedEventArgs e)
        {
            //if (e.Source is Button)
            //{
            //	Button b = e.Source as Button;
            //	// 导入逻辑
            //	if ("导入".Equals(b.Content))
            //	{
            //		System.Windows.Forms.OpenFileDialog fie = new System.Windows.Forms.OpenFileDialog();
            //		fie.Title = "导入清单规则";
            //		fie.Filter = "Excel|*.xls|Excel|*.xlsx";
            //		//获取选择的路径
            //		string str = fie.FileName;
            //		//用户点击打开后执行的逻辑
            //		if (fie.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //		{
            //			//MessageBox.Show(fie.FileName);
            //			MessageBox.Show("功能正在开发中...");
            //		}

            //	}
            //	// 导出逻辑
            //	if ("导出".Equals(b.Content))
            //	{
            //		System.Windows.Forms.SaveFileDialog s = new System.Windows.Forms.SaveFileDialog();
            //		s.Filter = "Excel|*.xls|Excel|*.xlsx";
            //		s.Title = "导出清单规则";
            //		s.DefaultExt = "Excel|*.xls";
            //		//获取文默认件扩展名
            //		// string str = s.DefaultExt;
            //		//用户点击"保存"后执行的逻辑
            //		if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //		{
            //			//获取保存的目录
            //			string fileName = s.FileName;
            //			foreach (RulesNode rn in rulesNodeList)
            //			{

            //			}
            //			MessageBox.Show("功能正在开发中...");

            //		}
            //	}
            //	// 恢复默认逻辑
            //	if ("默认".Equals(b.Content))
            //	{
            //		MessageBoxResult mr = MessageBox.Show("此操作将重置数据库为默认值，且不可恢复，确定吗？", "提示", MessageBoxButton.OKCancel);
            //		if (mr == MessageBoxResult.OK)
            //		{
            //			RulesTree rt = new RulesTree(userName);
            //			if (rt.setDefault())
            //			{
            //				MessageBox.Show("初始化成功", "提示");
            //			}
            //			else
            //			{
            //				MessageBox.Show("初始化失败", "提示");
            //			}
            //		}
            //	}
            //}
        }

        // 初始化数据
        private void excelDataInitialization()
        {
            if (backWork.IsBusy)
            {
                MessageBox.Show("当前有未计算完成的任务，请等待任务处理完成", "提示");
            }
            else
            {
                loadExcelButton.Visibility = Visibility.Collapsed;
                Label1.Visibility = Visibility.Visible;
                ProgressBar.Visibility = Visibility.Visible;
                backWork.RunWorkerAsync();
            }
        }

        //正在执行
        void backWork_DoWork(object sender, DoWorkEventArgs e)
        {
            // 当前Document的数据
            Document doc = uiApp.ActiveUIDocument.Document;
            List<excelData> excelDataList = ElementsData.getExcelDataList(doc, backWork);
            if (excelDataList.Count != 0 && excelDataList != null)
            {
                List = new ObservableCollection<excelData>(excelDataList);
            }
            // 链接中Document的数据
            List<excelData> excelDataListFromLinks;
            FilteredElementCollector collector = new FilteredElementCollector(doc);
            ElementClassFilter LinkFilter = new ElementClassFilter(typeof(RevitLinkInstance));
            FilteredElementIterator linkIterator = collector.WherePasses(LinkFilter).GetElementIterator();
            while (linkIterator.MoveNext())
            {
                RevitLinkInstance LinkInstance = linkIterator.Current as RevitLinkInstance;
                // 判断是否已加载
                RevitLinkType linkType = doc.GetElement(LinkInstance.GetTypeId()) as RevitLinkType;
                if (linkType.GetLinkedFileStatus() != LinkedFileStatus.Loaded) continue;

                Document LinkDoc = LinkInstance.GetLinkDocument();
                // 链接中的原始数据
                if (LinkDoc != null)
                {
                    excelDataListFromLinks = ElementsData.getExcelDataList(LinkDoc, backWork, "link");
                    if (excelDataListFromLinks.Count != 0)
                    {
                        ListFromLinks = new ObservableCollection<excelData>(excelDataListFromLinks);
                    }
                }
            }
        }
        // 百分比
        private void BackWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if ("link".Equals(e.UserState))
                Label1.Content = "正在计算链接模型...(" + Convert.ToString(e.ProgressPercentage) + "%)";
            else
                Label1.Content = "正在计算...(" + Convert.ToString(e.ProgressPercentage) + "%)";
            ProgressBar.Value = e.ProgressPercentage;
        }
        //执行完
        void backWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //初始化数据
            // 获取工程名称
            projectName = GetProjectName();
            this.ProjectName.Text = projectName;
            if (ListFromLinks.Count == 0)
            {
                // 初始化不含Revit链接的专业树
                categoryTreeView.ItemsSource = CategoryTree.getCategoryTree(List);
                // 初始化包不含Revit链接的数据
                excelDataByCategoryTree categoryTree = new excelDataByCategoryTree(List);
                excelListByCategory = categoryTree.getAll();
                ListView1.ItemsSource = excelListByCategory;
            }
            else
            {
                Links.IsChecked = true;
            }

            Label1.Visibility = Visibility.Collapsed;
            ProgressBar.Visibility = Visibility.Collapsed;
            ListView1.Visibility = System.Windows.Visibility.Visible;
        }

        /// <summary>
        /// 根据字段排序列表 
        /// </summary>
        /// <param name="field">字段</param>
        private void viewSort(string field, string SortDirection)
        {
            if (!string.IsNullOrEmpty(field) && !string.IsNullOrEmpty(SortDirection))
            {
                try
                {
                    // 初始化视图数据
                    viewForSort = CollectionViewSource.GetDefaultView(ListView1.ItemsSource);
                    // 设置视图的区域性信息为当前区域性对象
                    viewForSort.Culture = CultureInfo.CurrentCulture;
                    // viewForSort = CollectionViewSource.GetDefaultView(ListView1.ItemsSource);
                    if ("升序".Equals(SortDirection))
                    {
                        SortDescription sd = new SortDescription(field, ListSortDirection.Ascending);
                        viewForSort.SortDescriptions.Add(sd);
                    }
                    else if ("降序".Equals(SortDirection))
                    {
                        SortDescription sd = new SortDescription(field, ListSortDirection.Descending);
                        viewForSort.SortDescriptions.Add(sd);
                    }

                    //viewForSort.SortDescriptions.Clear();ListSortDirection SortDirection
                    viewForSort.Refresh();
                }
                catch (Exception e1)
                {
                    TaskDialog.Show("错误", e1.Message);
                }
            }
        }

        // 数据表格添加行号
        private void ExcelDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = (e.Row.GetIndex() + 1).ToString();
        }

        // 鼠标放到按钮图片上
        private void Image_MouseEnter(object sender, MouseEventArgs e)
        {
            var img = sender as System.Windows.Controls.Image;
            img.Width = 30;
            img.Height = 30;
            img.Margin = new Thickness(2, 0, 0, 0);
        }

        // 鼠标离开按钮图片
        private void Image_MouseLeave(object sender, MouseEventArgs e)
        {
            var img = sender as System.Windows.Controls.Image;
            img.Width = 28;
            img.Height = 28;
            img.Margin = new Thickness(4, 0, 0, 0);
        }

        // 窗体的最小化及恢复正常事件
        private void Window_StateChanged(object sender, EventArgs e)
        {
            // 发生过扣减，提示用户是否刷新数据
            if (WindowState == WindowState.Normal && isLianjieDone &&
                ListView1.Visibility == System.Windows.Visibility.Visible)
            {
                MessageBoxResult r = MessageBox.Show("检测到清单规则发生变化，模型已修改，是否重新计算？", "提示", MessageBoxButton.YesNo);
                if (r == MessageBoxResult.Yes)
                {
                    excelDataInitialization();
                }

                this.isLianjieDone = false;
            }
        }

        // 重写属性改变
        public event PropertyChangedEventHandler PropertyChanged;

        public virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private void mdbTest_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MdbHelper mh = new MdbHelper("D:\\计算规则.mdb");
                mh.GetDataTable("select * from sys_cpt_Adjustable_devariable");
            }
            catch (Exception)
            {
            }
        }

        // 过滤器选项变化
        private void filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox)
            {
                ComboBox cb = sender as ComboBox;
                if (cb.Name == "A1" && cb.SelectedValue == null)
                {
                    //A2.Text = A3.Text = null;
                    A2.IsEnabled = false;
                    A3.IsEnabled = false;
                }

                if (cb.Name == "A1" && cb.SelectedValue != null)
                {
                    A2.IsEnabled = true;
                    A3.IsEnabled = true;
                }

                if (cb.Name == "B1" && cb.SelectedValue == null)
                {
                    B2.IsEnabled = false;
                    B3.IsEnabled = false;
                }

                if (cb.Name == "B1" && cb.SelectedValue != null)
                {
                    B2.IsEnabled = true;
                    B3.IsEnabled = true;
                }

                if (cb.Name == "C1" && cb.SelectedValue == null)
                {
                    C2.IsEnabled = false;
                    C3.IsEnabled = false;
                }

                if (cb.Name == "C1" && cb.SelectedValue != null)
                {
                    C2.IsEnabled = true;
                    C3.IsEnabled = true;
                }
            }
        }

        // 排序选项变化
        private void order_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox)
            {
                ComboBox cb = sender as ComboBox;
                if (cb.Name == "OrderA1" && cb.SelectedValue == null)
                {
                    OrderA2.IsEnabled = false;
                }

                if (cb.Name == "OrderA1" && cb.SelectedValue != null)
                {
                    OrderA2.IsEnabled = true;
                }

                if (cb.Name == "OrderB1" && cb.SelectedValue == null)
                {
                    OrderB2.IsEnabled = false;
                }

                if (cb.Name == "OrderB1" && cb.SelectedValue != null)
                {
                    OrderB2.IsEnabled = true;
                }

                if (cb.Name == "OrderC1" && cb.SelectedValue == null)
                {
                    OrderC2.IsEnabled = false;
                }

                if (cb.Name == "OrderC1" && cb.SelectedValue != null)
                {
                    OrderC2.IsEnabled = true;
                }
            }
        }

        private void exportButton_Click(object sender, RoutedEventArgs e)
        {
            // 需要保存的数据
            List<excelData> exportList = this.ListView1.Items.Cast<object>().Select(x => x as excelData).ToList();
            if (exportList != null && exportList.Count != 0)
            {
                System.Windows.Forms.SaveFileDialog s = new System.Windows.Forms.SaveFileDialog();
                s.Filter = "Excel|*.xls|Excel|*.xlsx";
                s.Title = "导出清单表";
                s.DefaultExt = "Excel|*.xls";
                //获取文默认件扩展名
                // string str = s.DefaultExt;
                //用户点击"保存"后执行的逻辑
                if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    // 保存的目录
                    string fileName = s.FileName;

                    /// 导出逻辑
                    IWorkbook workbook = new HSSFWorkbook();
                    ISheet sheet = workbook.CreateSheet("Sheet1");
                    // 导出的字段
                    List<ComboBoxPairs> dateType = selectDateDictionary.DateType1();
                    //PropertyInfo[] pross = new excelData().GetType().GetProperties();

                    // 处理标题 第一行
                    ICellStyle style = workbook.CreateCellStyle();
                    style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
                    style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                    IFont font = workbook.CreateFont();
                    font.IsBold = true;
                    font.FontHeightInPoints = 14;
                    style.SetFont(font);
                    //style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Double;
                    //style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Double;
                    //style.BorderRight = NPOI.SS.UserModel.BorderStyle.Double;
                    //style.BorderTop = NPOI.SS.UserModel.BorderStyle.Double;
                    IRow row0 = sheet.CreateRow(0);
                    ICell row0Cell = row0.CreateCell(0, CellType.String);
                    row0Cell.SetCellValue("分部分项工程量清单");
                    row0Cell.CellStyle = style;
                    // 合并单元格
                    sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dateType.Count));

                    // 处理项目名称 第二行
                    IRow row1 = sheet.CreateRow(1);
                    ICell row1Cell = row1.CreateCell(0, CellType.String);
                    row1Cell.SetCellValue("工程名称：" + ProjectName.Text);


                    // 处理表头 第三行
                    IRow row2 = sheet.CreateRow(2);
                    ICell row2Cell = null;
                    row2Cell = row2.CreateCell(0, CellType.String);
                    row2Cell.SetCellValue("序号");

                    for (int i = 0; i < dateType.Count; i++)
                    {
                        row2Cell = row2.CreateCell(i + 1, CellType.String);
                        row2Cell.SetCellValue(dateType[i]._Value);
                    }

                    // 处理内容 第四行开始
                    ICell cellContent = null;
                    for (int i = 0; i < exportList.Count; i++)
                    {
                        IRow row3 = sheet.CreateRow(i + 3);
                        // 处理序号
                        cellContent = row3.CreateCell(0, CellType.String);
                        cellContent.SetCellValue((i + 1).ToString());
                        // 处理其他字段
                        for (int j = 0; j < dateType.Count; j++)
                        {
                            string excelValue = string.Empty;
                            string title = dateType[j]._Value;
                            //if (title.Equals("序号"))
                            //{
                            //    excelValue = list[i].Id.ToString();
                            //}
                            if (title.Equals("项目编号"))
                            {
                                excelValue = exportList[i].Code.ToString();
                            }
                            else if (title.Equals("项目名称"))
                            {
                                excelValue = exportList[i].Name.ToString();
                            }
                            else if (title.Equals("项目特征"))
                            {
                                excelValue = exportList[i].Features.ToString();
                            }
                            else if (title.Equals("工程量名称"))
                            {
                                excelValue = exportList[i].Quantitiesname.ToString();
                            }
                            else if (title.Equals("工程数量"))
                            {
                                excelValue = exportList[i].Num.ToString();
                            }
                            else if (title.Equals("计量数量"))
                            {
                                excelValue = exportList[i].NumCount.ToString();
                            }
                            else if (title.Equals("计量单位"))
                            {
                                excelValue = exportList[i].Company.ToString();
                            }
                            else
                            {
                                excelValue = string.Empty;
                            }

                            cellContent = row3.CreateCell(j + 1, CellType.String);
                            cellContent.SetCellValue(excelValue);
                        }
                    }

                    // 创建文件
                    try
                    {
                        FileStream file = new FileStream(fileName, FileMode.Create);
                        workbook.Write(file);
                        file.Close();
                        workbook.Close();
                        MessageBox.Show("导出完成", "提示");
                    }
                    catch (Exception e2)
                    {
                        MessageBox.Show(e2.Message, "提示");
                    }
                }
            }
            else
            {
                MessageBox.Show("当前表格中没有数据", "提示");
            }
        }

        private void ReleaseExcelObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show(ex.Message);
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}